package jxjc

import (
	"fmt"
	"io"
	"net/http"
	"os"
	"strings"
)

const (
	uploadPath       = "../frontEnd/public"  // 固定文件名保存路径
	uploadPathWithTS = "../frontEnd/uploads" // 带时间戳文件保存路径
	maxUploadSize    = 10 << 20              // 最大上传大小为10MB
)

func Flask() {
	http.HandleFunc("/upload", uploadHandler)
	fmt.Println("Server started at port 6088")
	if err := http.ListenAndServe(":6088", nil); err != nil {
		fmt.Println("Error starting server:", err)
	}
}

func uploadHandler(w http.ResponseWriter, r *http.Request) {
	// 限制上传大小
	r.Body = http.MaxBytesReader(w, r.Body, maxUploadSize)
	if err := r.ParseMultipartForm(maxUploadSize); err != nil {
		http.Error(w, "The uploaded file is too big. Please choose a file that's less than 10MB in size", http.StatusBadRequest)
		return
	}

	// 获取上传的文件
	file, handler, err := r.FormFile("file")
	if err != nil {
		http.Error(w, "Error retrieving the file", http.StatusInternalServerError)
		return
	}
	defer file.Close()

	// 根据文件名选择保存路径
	savePath := uploadPath // 默认保存到 public 文件夹
	if strings.Contains(handler.Filename, "linuxcheck_") {
		savePath = uploadPathWithTS // 如果文件名包含 "linuxcheck_" 则保存到 uploads 文件夹
	}

	// 创建上传目录（如果不存在）
	if _, err := os.Stat(savePath); os.IsNotExist(err) {
		os.Mkdir(savePath, 0755)
	}

	// 创建上传文件
	dst, err := os.Create(fmt.Sprintf("%s/%s", savePath, handler.Filename))
	if err != nil {
		http.Error(w, "Error creating the file", http.StatusInternalServerError)
		return
	}
	defer dst.Close()

	// 保存文件
	if _, err := io.Copy(dst, file); err != nil {
		http.Error(w, "Error saving the file", http.StatusInternalServerError)
		return
	}

	fmt.Fprintf(w, "File uploaded successfully: %s", handler.Filename)
}
